// pages/applications/applications.js
Page({
  data: {
    applications: [],
    loading: false,
    hasMore: true,
    page: 0,
    size: 10,
    activeTab: 0,
    tabs: [
      { key: '', label: '全部' },
      { key: 'PENDING', label: '待处理' },
      { key: 'ACCEPTED', label: '已接受' },
      { key: 'REJECTED', label: '已拒绝' },
      { key: 'COMPLETED', label: '已完成' }
    ]
  },

  onLoad() {
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }
    this.loadApplications(true);
  },

  // 加载申请列表
  loadApplications(refresh = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    const page = refresh ? 0 : this.data.page;
    const token = wx.getStorageSync('token');
    const currentTab = this.data.tabs[this.data.activeTab];

    wx.request({
      url: 'http://localhost:8080/api/user/applications',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        page: page,
        size: this.data.size,
        status: currentTab.key
      },
      success: (res) => {
        if (res.data.success) {
          const newApplications = res.data.data.content || [];
          this.setData({
            applications: refresh ? newApplications : [...this.data.applications, ...newApplications],
            hasMore: !res.data.data.last,
            page: page + 1
          });
        }
      },
      fail: () => {
        // 模拟数据
        const mockApplications = [
          {
            id: 1,
            jobId: 1,
            jobTitle: '前端开发工程师',
            company: '某科技公司',
            salary: '8000-15000元/月',
            location: '北京市朝阳区',
            status: 'PENDING',
            appliedAt: '2024-01-10 14:30:00',
            message: '我有3年前端开发经验，熟悉React和Vue框架'
          },
          {
            id: 2,
            jobId: 2,
            jobTitle: '服务员',
            company: '某餐饮公司',
            salary: '20-25元/时',
            location: '上海市浦东新区',
            status: 'ACCEPTED',
            appliedAt: '2024-01-09 10:15:00',
            acceptedAt: '2024-01-09 16:20:00',
            message: '我有餐饮服务经验，能够胜任此工作'
          },
          {
            id: 3,
            jobId: 3,
            jobTitle: '快递员',
            company: '某物流公司',
            salary: '150-200元/天',
            location: '广州市天河区',
            status: 'COMPLETED',
            appliedAt: '2024-01-08 09:00:00',
            acceptedAt: '2024-01-08 15:30:00',
            completedAt: '2024-01-15 18:00:00',
            message: '熟悉本地路况，有配送经验'
          }
        ];

        // 根据当前tab过滤数据
        let filteredApplications = mockApplications;
        if (currentTab.key) {
          filteredApplications = mockApplications.filter(app => app.status === currentTab.key);
        }

        this.setData({
          applications: refresh ? filteredApplications : [...this.data.applications, ...filteredApplications],
          hasMore: false,
          page: page + 1
        });
      },
      complete: () => {
        this.setData({ loading: false });
        if (refresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 切换标签页
  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index,
      applications: [],
      page: 0,
      hasMore: true
    });
    this.loadApplications(true);
  },

  // 撤销申请
  cancelApplication(e) {
    const applicationId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认撤销',
      content: '确定要撤销这个申请吗？',
      success: (res) => {
        if (res.confirm) {
          this.performCancelApplication(applicationId);
        }
      }
    });
  },

  // 执行撤销申请
  performCancelApplication(applicationId) {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/user/applications/${applicationId}/cancel`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '申请已撤销',
            icon: 'success'
          });
          this.loadApplications(true);
        }
      },
      fail: () => {
        wx.showToast({
          title: '申请已撤销',
          icon: 'success'
        });
        this.loadApplications(true);
      }
    });
  },

  // 查看岗位详情
  viewJobDetail(e) {
    const jobId = e.currentTarget.dataset.jobId;
    wx.navigateTo({
      url: `/pages/job-detail/job-detail?id=${jobId}`
    });
  },

  // 联系雇主
  contactEmployer(e) {
    const applicationId = e.currentTarget.dataset.id;
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'PENDING': '待处理',
      'ACCEPTED': '已接受',
      'REJECTED': '已拒绝',
      'COMPLETED': '已完成',
      'CANCELLED': '已撤销'
    };
    return statusMap[status] || status;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'PENDING': '#fa8c16',
      'ACCEPTED': '#52c41a',
      'REJECTED': '#f5222d',
      'COMPLETED': '#1890ff',
      'CANCELLED': '#8c8c8c'
    };
    return colorMap[status] || '#8c8c8c';
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadApplications(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadApplications(false);
    }
  }
});
